<template>
  <el-card class="form-container" shadow="never">
    <el-form :model="brand" :rules="rules" ref="brandFrom" label-width="auto">
      <el-form-item label="品牌名称：" prop="name">
        <el-input v-model="brand.name"></el-input>
      </el-form-item>
      <el-form-item label="品牌首字母：">
        <el-input v-model="brand.firstLetter"></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO：" prop="logo">
        <single-upload v-model="brand.logo"></single-upload>
      </el-form-item>
      <el-form-item label="品牌专区大图：">
        <single-upload v-model="brand.bigPic"></single-upload>
      </el-form-item>
      <el-form-item label="品牌故事：">
        <el-input placeholder="请输入内容" type="textarea" v-model="brand.brandStory" :autosize="true"></el-input>
      </el-form-item>
      <el-form-item label="排序：" prop="sort">
        <el-input v-model.number="brand.sort"></el-input>
      </el-form-item>
      <el-form-item label="是否显示：">
        <el-switch v-model="brand.showStatus" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="品牌制造商：">
        <el-switch v-model="brand.factoryStatus" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button v-if="!route.query.id" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { createBrand, getBrand, updateBrand } from '@/api/brand'
import type { Brand } from '@/models/brand'

defineOptions({ name: 'BrandUpsert' })

const rules: FormRules<Brand> = {
  name: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur' },
  ],
  logo: [{ required: true, message: '请输入品牌logo', trigger: 'blur' }],
  sort: [{ type: 'number', message: '排序必须为数字' }],
}
const route = useRoute()
const router = useRouter()

const brand = ref<Brand>({})
const brandFrom = ref<FormInstance>()
const initData = async () => {
  if (route.query.id) {
    const res = await getBrand(Number(route.query.id))
    brand.value = res.data.data
  } else {
    resetForm()
  }
}
const onSubmit = async () => {
  await brandFrom.value?.validate()
  await ElMessageBox.confirm('是否提交数据', '提示', { type: 'warning' })
  if (brand.value.id) {
    await updateBrand(brand.value.id, brand.value)
    ElMessage.success('修改成功！')
  } else {
    await createBrand(brand.value)
    ElMessage.success('提交成功')
  }
  router.back()
  brandFrom.value?.resetFields()
}
const resetForm = () => {
  brandFrom.value?.resetFields()
  brand.value = {}
}
initData()
</script>
<style></style>
